package com.ghy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ghy.entity.Ident;
import com.ghy.mapper.IdentMapper;
import com.ghy.utils.Exception.QueryException;
import com.ghy.utils.Exception.SaveException;
import com.ghy.utils.Exception.UpdateException;
import com.ghy.utils.File.InterceptorConfig;
import com.ghy.utils.File.fileUpload;
import com.ghy.utils.Message;
import com.ghy.utils.QRCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Slf4j
@Transactional
@Service
public class IdentService extends ServiceImpl<IdentMapper, Ident> {
    @Resource
    private IdentMapper identMapper;

    public void saveIdent(Ident ident, MultipartFile picture, MultipartFile video){
        if ( !ObjectUtils.isEmpty(picture) ) {
            File file = new File( InterceptorConfig.basePath);
            String serverPath = file.getAbsolutePath();
            String src = fileUpload.img("ident", picture,serverPath );
            ident.setPictureUrl ( src );
        }
        if (!ObjectUtils.isEmpty(video)) {
            File file = new File(InterceptorConfig.basePath);
            String serverPath = file.getAbsolutePath();
            String src = fileUpload.img("ident" ,video, serverPath);
            ident.setVideoUrl ( src );
        }
        boolean insert = this.save(ident);
        if (!insert) {
            throw new SaveException("上报数据异常，请重新填写");
        }

    }

    public void deleteIdent(Long id){
        boolean remove = this.removeById(id);
        if (!remove) {
            throw new SaveException("删除数据异常，请重新填写");
        }
    }

    public boolean updateIdent(Ident ident,MultipartFile picture,MultipartFile video){
        if (picture != null) {
            File file = new File( InterceptorConfig.basePath);
            String serverPath = file.getAbsolutePath();
            String src = fileUpload.img("ident", picture,serverPath );
             ident.setPictureUrl ( src );
        }
        if (video  != null) {
            File file = new File(InterceptorConfig.basePath);
            String serverPath = file.getAbsolutePath();
              String src = fileUpload.img("ident" ,video, serverPath);
              ident.setVideoUrl ( src );
        }
        boolean update = this.updateById(ident);
        if (!update  ) {
            throw new UpdateException("更改失败");
        }
        return update;
    }


    public Map findById(Long id, String url, HttpServletResponse response) throws Exception {
        Ident ident = identMapper.selectById(id);
        if (ident == null) {
            throw new QueryException("查询异常，请检查您传入的数据");
        }
        Map<String, Object> map = new HashMap<String, Object> ();

        map.put("entity", ident);
        if (url != null && !"".equals(url)) {
            ServletOutputStream stream = response.getOutputStream();
            //使用工具类生成二维码
            //BufferedImage bufferedImage = QRCodeUtil.encodeImg("http://121.34.249.123:8002/#/login", stream);
            BufferedImage bufferedImage = QRCodeUtil.encodeImg(url, stream);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", baos);
            baos.flush();
            //使用toByteArray()方法转换成字节数组
            byte[] imageInByte = baos.toByteArray();
            baos.close();

            //进行base64位加密
            BASE64Encoder encoder = new BASE64Encoder();
            String qrImg = encoder.encode(imageInByte);
            map.put("image", qrImg);
            System.out.println (qrImg);
        }
        return map;
    }

//可以模糊匹配
    public Page<Ident> listIdent(Page page,Ident ident) {//里面包含了  sysType


        Map<String, Object> map = new HashMap<String, Object>();
        QueryWrapper<Ident> sectionQueryWrapper = new QueryWrapper<> ();
        if (ident.getContent() != null && !ident.getContent().equals("")) {
            sectionQueryWrapper.like("content",ident.getContent());
        }

        sectionQueryWrapper.eq("sys_type",ident.getSysType());
        Page<Ident> page1=this.page ( page,sectionQueryWrapper );

        //如果最后一页为0条数据则回显上一页
        if(page1.getRecords ().size ()==0 && page1.getCurrent ()>1){
            page.setCurrent ( page1.getCurrent ()-1 );
            page1 = this.page(page, sectionQueryWrapper);

        }

        return page1;
    }

    public List<String> findSelect() {
        List<Ident> list=this.identMapper.selectList ( null );
        List<String> list1=list.stream ().map ( Ident::getSysType ).distinct ().collect ( Collectors.toList () );
        return list1;
    }

    public void updateSysType(String frontType,String sysType) {
      this.identMapper.updateSysType(frontType,sysType);

    }

    public void deleteType(String sysType) {
        this.identMapper.deleteType(sysType);
    }
}
